# main.py
from PyQt6 import QtWidgets,QtCore
from PyQt6.QtCore import pyqtSlot , Qt , pyqtSignal
from PyQt6.QtGui import QFont
import sys
import os
import platform
import subprocess
import threading
import logging

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s')

from .Ui_tcp_con_cfg import Ui_Dialog  # 这是 pyuic6 自动生成的类

class tcp_con_cfg_dialog(QtWidgets.QDialog):    
    config_applied = pyqtSignal(dict)  # 信号，传出配置字典
    def __init__(self):
        super().__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        # 替代默认连接
        self.ui.buttonBox.accepted.disconnect()
        self.ui.buttonBox.rejected.disconnect()

        self.ui.buttonBox.accepted.connect(self.on_ok_clicked)
        self.ui.buttonBox.rejected.connect(self.on_reject_clicked)
        # 自动开始扫描
        self.start_scan()
    def on_ok_clicked(self):
        config = {
            'camera_1': {
                'ip': self.ui.comboBox.currentText(),
                'data_port': int(self.ui.lineEdit.text()),
                'mode':self.ui.checkBox.isChecked()
            },
            'camera_2': {
                'ip': self.ui.comboBox_2.currentText(),
                'data_port': int(self.ui.lineEdit_3.text()),
                'mode':self.ui.checkBox_2.isChecked()
            },
            'dobot': {
                'ip': self.ui.comboBox_3.currentText(),
                'dashboard_port': int(self.ui.lineEdit_6.text()),
                'move_port': int(self.ui.lineEdit_7.text()),
                'feed_port': int(self.ui.lineEdit_8.text()),
                'mode':self.ui.checkBox_3.isChecked()
            }
        }

        logging.debug("config data: %s", config)
        self.config_applied.emit(config)  # 发送信号
        self.accept()
    def on_reject_clicked(self):
        # 关闭窗口
        logging.warning("ip configuration canceled.")
        self.reject()
    def start_scan(self):
        # 开一个线程防止阻塞界面
        logging.info("Begin scanning local devices...")
        threading.Thread(target=self.scan_and_fill, daemon=True).start()

    def scan_and_fill(self):
        ip_list = scan_local_ips("127.0.0.")
        QtCore.QMetaObject.invokeMethod(
            self, "update_comboboxes", QtCore.Qt.ConnectionType.QueuedConnection,
            QtCore.Q_ARG(list, ip_list)
        )

    @QtCore.pyqtSlot(list)
    def update_comboboxes(self, ip_list):
        for combo in [self.ui.comboBox, self.ui.comboBox_2, self.ui.comboBox_3]:
            combo.clear()
            combo.addItems(ip_list)
        logging.info(f"Scanning done, found {len(ip_list)} devices.")

        # 恢复按钮状态（可选）
        # self.ui.btn_scan.setEnabled(True)
        # self.ui.btn_scan.setText("重新扫描")
def scan_local_ips(ip_prefix="192.168.1.", start=1, end=254, timeout=100):
    alive = []
    threads = []
    system = platform.system().lower()
    param = "-n" if system == "windows" else "-c"

    def ping(ip):
        try:
            kwargs = {
                "stdout": subprocess.DEVNULL,
                "stderr": subprocess.DEVNULL,
            }

            # 如果是 Windows，添加隐藏窗口的 flag
            if system == "windows":
                kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW

            result = subprocess.run(
                ["ping", param, "1", "-w", str(timeout), ip],
                **kwargs
            )
            logging.debug(f"ping {ip} result: {result.returncode}")
            if result.returncode == 0:
                alive.append(ip)
        except:
            pass

    for i in range(start, end + 1):
        ip = f"{ip_prefix}{i}"
        t = threading.Thread(target=ping, args=(ip,))
        threads.append(t)
        t.start()

    for t in threads:
        t.join()

    return alive
# 启动程序
def main():
    os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"

    app = QtWidgets.QApplication(sys.argv)

    # 可选：根据 DPI 缩放字体
    screen = app.primaryScreen()
    dpi = screen.logicalDotsPerInch()
    scale = dpi / 96.0
    font = QFont("Microsoft YaHei", int(10 * scale))
    app.setFont(font)

    dlg = tcp_con_cfg_dialog()
    dlg.show()
    sys.exit(app.exec())

def run():
    app = QtWidgets.QApplication.instance()
    if app is not None:
        screen = app.primaryScreen()
        dpi = screen.logicalDotsPerInch()
        scale = dpi / 96.0
        font = QFont("Microsoft YaHei", int(10 * scale))
        app.setFont(font)

    dlg = tcp_con_cfg_dialog()
    # dlg.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
    # dlg.exec()
    return dlg

if __name__ == '__main__':
    main()